using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Imaging;
using System.Reflection;
using System.Resources;
using System.Text;
using System.Windows.Forms;
using Infragistics.UltraChart.Resources.Appearance;
using Infragistics.UltraChart.Shared.Events;
using Infragistics.UltraChart.Shared.Styles;
using Infragistics.Win;
using Infragistics.Win.UltraWinChart;
using Infragistics.Win.UltraWinTabControl;
using Infragistics.Win.UltraWinTabs;
using Infragistics.Win.UltraWinToolTip;

namespace PluginFrame
{
    public abstract class AbstactCurveView : IPlugin, IProvideService, IPcrExperimentViewControl
    {
        protected ResourceManager mResourceManager;

        protected IApplication mApplication;

        protected string mName = "";

        protected string mDescription = "";

        protected int mIndex;

        protected string[] mDetectionTypes;

        protected IPcrSystemService mPcrSystemService;

        protected IPcrDataService mPcrDataService;

        protected IConfigurationService mConfigurationService;

        protected IMiscService mMiscService;

        protected IPcrOptionService mPcrOptionService;

        protected IPcrLogService mPcrLogService;

        protected IPcrDataFile mPcrDataFile;

        protected UltraTab mTabPage;

        protected UltraTabControl mCurveTabControl;

        protected ContextMenuStrip mChartMenu;

        protected ToolStripMenuItem[] mMenuCurveColor;

        protected SaveFileDialog mSavePictureDialog;

        protected string mTabPageName;

        protected string mTabPageControlName;

        protected UltraToolTipManager mToolTipManager;

        protected IPcrExperiment mPcrExperiment;

        protected Dictionary<string, bool> mTooltipDisplay;

        protected Dictionary<string, string> mTooltipColumn;

        public IApplication Application
        {
            get
            {
                return mApplication;
            }
            set
            {
                mApplication = value;
            }
        }

        public int Index
        {
            get
            {
                return mIndex;
            }
            set
            {
                mIndex = value;
            }
        }

        public string Name
        {
            get
            {
                return mName;
            }
            set
            {
                mName = value;
            }
        }

        public string Description
        {
            get
            {
                return mDescription;
            }
            set
            {
                mDescription = value;
            }
        }

        public event EventHandler<EventArgs> PluginEvent;

        public void Execute(object[] context)
        {
        }

        public object ProvideService()
        {
            return null;
        }

        public virtual void UnLoad()
        {
            mApplication.RemoveService(mName);
        }

        public virtual void Load()
        {
            if (mApplication != null)
            {
                mApplication.AddService(mName, this);
                mMiscService = (IMiscService)mApplication.GetService("MiscService");
                mConfigurationService = (IConfigurationService)mApplication.GetService("ConfigurationService");
                mPcrSystemService = (IPcrSystemService)mApplication.GetService("PcrSystemService");
                mPcrOptionService = (IPcrOptionService)mApplication.GetService("PcrOptionService");
                mPcrLogService = (IPcrLogService)mApplication.GetService("PcrLogService");
                mDetectionTypes = mConfigurationService.GetDetectionTypeArray(PcrSystemType.AbsoluteAnalysis);
                InitializeChartMenu();
            }
        }

        public virtual void CreateControl(IPcrExperiment pcrExperiment)
        {
            mPcrDataFile = pcrExperiment.PcrStructure.PcrDataFile;
            mTabPage = new UltraTab();
            mCurveTabControl = new UltraTabControl();
            UltraTabPageControl ultraTabPageControl = new UltraTabPageControl();
            mTabPage.TabPage = ultraTabPageControl;
            mTabPage.Text = mTabPageName;
            mTabPage.Key = mTabPageName;
            mTabPage.Tag = pcrExperiment;
            ultraTabPageControl.Name = mTabPageName;
            ultraTabPageControl.Controls.Add(mCurveTabControl);
            ((ISupportInitialize)mCurveTabControl).BeginInit();
            mCurveTabControl.Dock = DockStyle.Fill;
            mCurveTabControl.Name = mTabPageControlName;
            mCurveTabControl.ViewStyle = ViewStyle.VisualStudio2005;
            mCurveTabControl.Style = UltraTabControlStyle.Wizard;
            mCurveTabControl.TabLayoutStyle = TabLayoutStyle.SingleRowAutoSize;
            mCurveTabControl.TabOrientation = TabOrientation.Default;
            mCurveTabControl.ScrollButtons = TabScrollButtons.Always;
            mCurveTabControl.AllowTabClosing = false;
            mCurveTabControl.AllowTabMoving = false;
            mCurveTabControl.BackColor = Color.LightGray;
            mCurveTabControl.ShowTabListButton = DefaultableBoolean.False;
            ((ISupportInitialize)mCurveTabControl).EndInit();
            mCurveTabControl.Text = "mCurveTabControl-" + mTabPage.Text;
            RefreshCurveTabs(new List<IPcrExperiment> { pcrExperiment });
        }

        public virtual UltraTab GetControl()
        {
            return mTabPage;
        }

        public virtual void SetVisible(bool isVisible)
        {
            mTabPage.Visible = isVisible;
        }

        public virtual void SetActive()
        {
            mTabPage.Active = true;
            mTabPage.Selected = true;
        }

        public virtual bool IsVisible()
        {
            return mTabPage.Visible;
        }

        public virtual void SwitchExperimentView(int experimentIndex)
        {
            if (experimentIndex >= 0 && experimentIndex < mCurveTabControl.Tabs.Count)
            {
                mCurveTabControl.SelectedTab = mCurveTabControl.Tabs[experimentIndex];
            }
        }

        public virtual bool GetCurveYAxialIsLog()
        {
            UltraChart ultraChart = (UltraChart)mCurveTabControl.ActiveTab.Tag;
            if (ultraChart != null)
            {
                AxisItem axisItem = ultraChart.CompositeChart.ChartAreas[0].Axes[1];
                return axisItem.NumericAxisType == NumericAxisType.Logarithmic;
            }
            return false;
        }

        public virtual void GetCurrentTabAxisRange(out double xMax, out double xMin, out double yMax, out double yMin)
        {
            UltraChart ultraChart = (UltraChart)mCurveTabControl.ActiveTab.Tag;
            if (ultraChart != null)
            {
                AxisItem axisItem = ultraChart.CompositeChart.ChartAreas[0].Axes[1];
                AxisItem axisItem2 = ultraChart.CompositeChart.ChartAreas[0].Axes[0];
                yMax = axisItem.RangeMax;
                yMin = axisItem.RangeMin;
                xMax = axisItem2.RangeMax;
                xMin = axisItem2.RangeMin;
            }
            else
            {
                yMax = 0.0;
                yMin = 0.0;
                xMax = 0.0;
                xMin = 0.0;
            }
        }

        public virtual void RefreshView(bool isRefreshCurrentTab, int currentTabIndex)
        {
            bool flag = true;
            foreach (UltraTab tab in mCurveTabControl.Tabs)
            {
                if (isRefreshCurrentTab && tab.Index != currentTabIndex)
                {
                    continue;
                }
                if (IsSetChartEnable())
                {
                    if (SetChartEnable(tab))
                    {
                        flag = false;
                    }
                }
                else
                {
                    flag = false;
                }
                AddCurveSeriesToChart(tab);
            }
            bool flag2 = true;
            foreach (UltraTab tab2 in mCurveTabControl.Tabs)
            {
                if (tab2.Visible)
                {
                    flag2 = false;
                    break;
                }
            }
            if (flag2 || flag)
            {
                mTabPage.Visible = false;
                mCurveTabControl.Visible = false;
            }
            else
            {
                mTabPage.Visible = true;
                mCurveTabControl.Visible = true;
            }
        }

        public virtual void AddPcrCellCurveToChart(List<IPcrCell> pcrCells, int currentTabIndex, bool isToClearChart, bool forceToInvisible)
        {
            UltraTab ultraTab = mCurveTabControl.Tabs[currentTabIndex];
            if (ultraTab == null)
            {
                return;
            }
            UltraChart ultraChart = (UltraChart)ultraTab.Tag;
            if (isToClearChart)
            {
                ultraChart.Series.Clear();
                for (int i = 0; i < ultraChart.CompositeChart.ChartLayers.Count; i++)
                {
                    ultraChart.CompositeChart.ChartLayers[i].Series.Clear();
                }
            }
            foreach (IPcrCell pcrCell in pcrCells)
            {
                if (pcrCell.Project == null)
                {
                    continue;
                }
                IProjectItem[] projectItems = pcrCell.Project.ProjectItems;
                foreach (IProjectItem projectItem in projectItems)
                {
                    if (projectItem != null && projectItem.ChannelConfiguration.IsAvailable && projectItem.ChannelConfiguration.IsSelected)
                    {
                        int position = projectItem.ChannelConfiguration.Position;
                        XYSeries cellCurveSeries = GetCellCurveSeries(pcrCell, position, isToClearChart);
                        if (cellCurveSeries != null && !ultraChart.CompositeChart.ChartLayers[position].Series.Contains(cellCurveSeries))
                        {
                            ultraChart.CompositeChart.ChartLayers[position].Series.Add(cellCurveSeries);
                            cellCurveSeries.Visible = !forceToInvisible;
                        }
                    }
                }
            }
        }

        public virtual void RefreshChartLayerLineStyle()
        {
            UltraTab ultraTab = mCurveTabControl.Tabs[0];
            if (ultraTab == null)
            {
                return;
            }
            UltraChart ultraChart = (UltraChart)ultraTab.Tag;
            IPcrExperiment pcrExperiment = (IPcrExperiment)ultraTab.TabPage.Tag;
            if (ultraChart == null || pcrExperiment == null)
            {
                return;
            }
            if (pcrExperiment.SystemType == PcrSystemType.Allele || pcrExperiment.CurveColorStyle == CurveColorStyle.Cell || pcrExperiment.CurveColorStyle == CurveColorStyle.Type)
            {
                int num = 0;
                {
                    foreach (ChartLayerAppearance item in (IEnumerable)ultraChart.CompositeChart.ChartLayers)
                    {
                        ((ScatterChartAppearance)item.ChartTypeAppearance).LineAppearance.DrawStyle = mConfigurationService.AmplificationLightCurveConfiguration.CurveDrawStyle[num++];
                    }
                    return;
                }
            }
            if (pcrExperiment.CurveColorStyle != CurveColorStyle.Channel)
            {
                return;
            }
            foreach (ChartLayerAppearance item2 in (IEnumerable)ultraChart.CompositeChart.ChartLayers)
            {
                ((ScatterChartAppearance)item2.ChartTypeAppearance).LineAppearance.DrawStyle = LineDrawStyle.Solid;
            }
        }

        protected virtual bool SetChartEnable(UltraTab curveTab)
        {
            IPcrExperiment pcrExperiment = (IPcrExperiment)curveTab.TabPage.Tag;
            UltraChart ultraChart = (UltraChart)curveTab.Tag;
            if (!IsChartEnable(pcrExperiment))
            {
                ultraChart.CompositeChart.ChartAreas[0].Axes[0].Visible = false;
                ultraChart.CompositeChart.ChartAreas[0].Axes[1].Visible = false;
                ultraChart.CompositeChart.ChartAreas[0].Axes[2].Visible = false;
                ultraChart.TitleLeft.Visible = false;
                ultraChart.TitleBottom.Visible = false;
                ultraChart.Enabled = false;
                return false;
            }
            ultraChart.CompositeChart.ChartAreas[0].Axes[0].Visible = true;
            ultraChart.CompositeChart.ChartAreas[0].Axes[1].Visible = true;
            ultraChart.CompositeChart.ChartAreas[0].Axes[2].Visible = true;
            ultraChart.TitleLeft.Visible = true;
            ultraChart.TitleBottom.Visible = true;
            ultraChart.Enabled = true;
            return true;
        }

        protected virtual XYSeries GetCellCurveSeries(IPcrCell pcrCell, int channelIndex, bool isToClearChart)
        {
            if (isToClearChart)
            {
                pcrCell.InitializeRawCurveSeries(channelIndex);
            }
            XYSeries rawCurveSeries = pcrCell.GetRawCurveSeries(channelIndex);
            if (rawCurveSeries == null)
            {
                pcrCell.InitializeRawCurveSeries(channelIndex);
                rawCurveSeries = pcrCell.GetRawCurveSeries(channelIndex);
            }
            return rawCurveSeries;
        }

        protected abstract void InitializeChartMenu();

        protected abstract UltraChart InitializeCurveChart(UltraTab curveTab, IPcrExperiment pcrExperiment);

        protected abstract bool IsChartEnable(IPcrExperiment pcrExperiment);

        protected abstract bool IsSetChartEnable();

        protected abstract void AddCurveSeriesToChart(UltraTab curveTab);

        protected virtual void InitializeToolTips(UltraChart chart)
        {
            mTooltipDisplay = mConfigurationService.AmplificationLightCurveConfiguration.TooltipDisplay;
            mTooltipColumn = mConfigurationService.AmplificationLightCurveConfiguration.TooltipColumnName;
            mToolTipManager = new UltraToolTipManager();
            mToolTipManager.AutoPopDelay = 5000;
            mToolTipManager.InitialDelay = 500;
            mToolTipManager.ToolTipTextStyle = ToolTipTextStyle.Formatted;
        }

        public virtual void RefreshCurveTabs(List<IPcrExperiment> pcrExperiments)
        {
            for (int i = 0; i < pcrExperiments.Count; i++)
            {
                if (!pcrExperiments[i].IsAvailable)
                {
                    continue;
                }
                List<UltraTab> list = AddCurveTabControlPages(pcrExperiments[i]);
                foreach (UltraTab item in list)
                {
                    UltraChart ultraChart = InitializeCurveChart(item, pcrExperiments[i]);
                    if (item != null)
                    {
                        item.TabPage.Controls.Add(ultraChart);
                        item.Tag = ultraChart;
                    }
                }
            }
        }

        protected virtual List<UltraTab> AddCurveTabControlPages(IPcrExperiment pcrExperiments)
        {
            List<UltraTab> list = new List<UltraTab>();
            UltraTab ultraTab = new UltraTab();
            UltraTabPageControl ultraTabPageControl2 = (ultraTab.TabPage = new UltraTabPageControl());
            ultraTab.Text = pcrExperiments.Name + " " + mTabPage.Key;
            ultraTab.Key = pcrExperiments.Name + " " + mTabPage.Key;
            ultraTabPageControl2.Name = pcrExperiments.Name + " " + mCurveTabControl.Name;
            mCurveTabControl.Controls.Add(ultraTabPageControl2);
            mCurveTabControl.Tabs.Add(ultraTab);
            ultraTabPageControl2.Tag = pcrExperiments;
            list.Add(ultraTab);
            return list;
        }

        protected virtual void ZoomChartCurve(bool isShowLogAxis)
        {
            UltraChart chart = mChartMenu.SourceControl as UltraChart;
            mPcrOptionService.ShowChartAxisZoomOptionForm(chart, isShowLogAxis);
        }

        protected virtual void SaveChartCurvePicture()
        {
            mSavePictureDialog = new SaveFileDialog();
            mSavePictureDialog.OverwritePrompt = true;
            mSavePictureDialog.DefaultExt = "bmp";
            mSavePictureDialog.Filter = "bmp file(*.bmp)|*.bmp";
            mSavePictureDialog.FileName = DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss") + ".bmp";
            if (mSavePictureDialog.ShowDialog() == DialogResult.OK)
            {
                PropertyInfo property = typeof(ImageFormat).GetProperty("Bmp");
                (mChartMenu.SourceControl as UltraChart).SaveTo(mSavePictureDialog.FileName, (ImageFormat)property.GetValue(null, null));
            }
        }

        protected virtual void chart_DataItemOver(object sender, ChartDataEventArgs e)
        {
            try
            {
                int result;
                int result2;
                if (string.IsNullOrEmpty(e.Primitive.Series.Key) || string.IsNullOrEmpty(e.Primitive.Series.Label) || !int.TryParse(e.Primitive.Series.Key, out result) || !int.TryParse(e.Primitive.Series.Label, out result2))
                {
                    return;
                }
                ICellIDPositionMap cellIDPositionMap = mPcrExperiment.PcrStructure.GetCellIDPositionMap(result);
                IPcrCell cellFromCellIDMap = mPcrExperiment.PcrStructure.GetCellFromCellIDMap(cellIDPositionMap);
                UltraChart control = sender as UltraChart;
                UltraToolTipInfo ultraToolTipInfo = new UltraToolTipInfo();
                List<string> list = new List<string>();
                List<string> list2 = new List<string>();
                int num = 0;
                StringBuilder stringBuilder = new StringBuilder();
                XYDataPoint point = e.Primitive.DataPoint as XYDataPoint;
                IEnumerator<string> enumerator = mTooltipDisplay.Keys.GetEnumerator();
                while (enumerator.MoveNext())
                {
                    if (!mTooltipDisplay[enumerator.Current])
                    {
                        continue;
                    }
                    string empty = string.Empty;
                    string text = enumerator.Current;
                    string text2 = mTooltipColumn[enumerator.Current];
                    IColumn column = null;
                    if (!string.IsNullOrEmpty(text2) && mPcrExperiment.ColumnConfiguration.ContainsKey(text2))
                    {
                        column = mPcrExperiment.ColumnConfiguration[text2].Tag as IColumn;
                    }
                    if (column != null)
                    {
                        empty = cellFromCellIDMap.GetCellInformation(text2, result2);
                        string cellInformation = cellFromCellIDMap.GetCellInformation("DetectionTypeKey", result2);
                        if (enumerator.Current.Equals(mResourceManager.GetString("SampleTypeString")))
                        {
                            text = mResourceManager.GetString("TypeString");
                        }
                        else if (enumerator.Current.Equals(mResourceManager.GetString("PropertyNameString")))
                        {
                            if (cellInformation.Equals(mDetectionTypes[1]))
                            {
                                if (mTooltipColumn.ContainsKey(text))
                                {
                                    text = mResourceManager.GetString("NameString");
                                    empty = cellFromCellIDMap.GetCellInformation(mTooltipColumn[text], result2);
                                }
                            }
                            else
                            {
                                text = mResourceManager.GetString("PropertyString");
                                empty = mMiscService.ConvertScientificString(empty, mConfigurationService.AnalysisConfiguration.ConcentrationFormatString);
                            }
                        }
                    }
                    else
                    {
                        empty = DisplayNAColumnTips(enumerator.Current, point);
                    }
                    if (text.Length > num)
                    {
                        num = text.Length;
                    }
                    list.Add(text);
                    list2.Add(empty);
                }
                for (int i = 0; i < list.Count; i++)
                {
                    int totalWidth = num - list[i].Length + 1;
                    string text3 = ":".PadLeft(totalWidth, ' ');
                    string value = list[i] + text3 + list2[i];
                    if (stringBuilder.Length > 0)
                    {
                        stringBuilder.AppendLine(value);
                    }
                    else
                    {
                        stringBuilder.AppendLine(value);
                    }
                }
                ultraToolTipInfo.ToolTipTextStyle = ToolTipTextStyle.Raw;
                ultraToolTipInfo.ToolTipText = stringBuilder.ToString();
                mToolTipManager.Enabled = true;
                mToolTipManager.SetUltraToolTip(control, ultraToolTipInfo);
                mToolTipManager.ShowToolTip(control);
            }
            catch (Exception ex)
            {
                mPcrLogService.ShowExceptionDialogBox(ex);
            }
        }

        protected virtual string DisplayNAColumnTips(string enumeratorString, XYDataPoint point)
        {
            if (enumeratorString.Equals(mResourceManager.GetString("CycleCountString")))
            {
                return point.ValueX.ToString("0.000");
            }
            if (enumeratorString.Equals("dRn") || enumeratorString.Equals(mResourceManager.GetString("RnString")))
            {
                return point.ValueY.ToString("0.000");
            }
            return string.Empty;
        }

        protected virtual void chart_DataItemOut(object sender, ChartDataEventArgs e)
        {
            try
            {
                mToolTipManager.HideToolTip();
                mToolTipManager.Enabled = false;
            }
            catch (Exception ex)
            {
                mPcrLogService.ShowExceptionDialogBox(ex);
            }
        }

        protected virtual void chartCurve_MouseClick(object sender, MouseEventArgs e)
        {
            try
            {
                if (e.Button == MouseButtons.Right)
                {
                    mChartMenu.Show(sender as UltraChart, e.Location);
                }
            }
            catch (Exception)
            {
            }
        }
    }
}
